package com.dys.controller;

import com.dys.service.UserService;
import com.dys.util.PageCom;
import com.dys.util.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/getUsers")
    public String getUser(Model model) {
        List<User> list = userService.getUsers();
        if(list.size() > 0)
            model.addAttribute("list",list);
        return "users";
    }

    @RequestMapping("/pageUserPage")
    public ModelAndView getUsersByPage(int pageIndex) {
        ModelAndView modelAndView = new ModelAndView();

        int userCount = userService.getUsersCount();
        int total = PageCom.getTotalPages(userCount,PageCom.PAGE_SIZE);
      //..........
        System.out.println("userCount " + userCount + " && "+ "PageSize "+PageCom.PAGE_SIZE);


        if(pageIndex < 1 ) pageIndex=1;
        if(pageIndex > total) pageIndex = total;

        Map<String, Integer> cond = new HashMap<>();
        cond.put("start",PageCom.PAGE_SIZE*(pageIndex - 1));
        cond.put("length",PageCom.PAGE_SIZE);

        //根据cond获取页数
        List<User> list = userService.getUsersByPage(cond);

        modelAndView.addObject("pageIndex",pageIndex);
        modelAndView.addObject("list",list);
        modelAndView.addObject("total",total);

        modelAndView.setViewName("users");
        return modelAndView;
    }
}
